package utils

import (
	"crypto/md5"
	"encoding/hex"
	"net"
	"os"
	"path/filepath"

	"github.com/urfave/cli"
)

// Config - running config
type Config struct {
	PcCode string
	Prog   string

	BasePath   string
	Etc        string
	EtcUser    string
	EtcTask    string
	EtcSession string
}

// News - new config
func (c Config) News() Config {
	c.PcCode = pcCode()
	c.Prog = os.Args[0]
	c.BasePath = filepath.Dir(c.Prog)

	return c
}

func pcCode() string {
	interfaces, err := net.Interfaces()
	if err != nil {
		return "0000000000000000000000000000000000000000000"
	}
	addr := ""
	for _, inter := range interfaces {
		addr += inter.HardwareAddr.String()
	}
	h := md5.New()
	h.Write([]byte(addr))
	return hex.EncodeToString(h.Sum(nil))
}

// Load - load config from args
func (c *Config) Load(context *cli.Context) {
	var temp = context.String("path")
	if filepath.IsAbs(temp) {
		c.BasePath = temp
	} else {
		c.BasePath = filepath.Join(c.BasePath, temp)
	}
	c.Etc = filepath.Join(c.BasePath, ".sgbm")
	c.EtcUser = filepath.Join(c.Etc, "user")
	c.EtcTask = filepath.Join(c.Etc, "task")
	c.EtcSession = filepath.Join(c.Etc, "session")
}
